﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using In.Api.Dto.InPatientWs;
using In.Api.Dto.LisWs;
using Newtonsoft.Json;
using OutDbContext;
using StackExchange.Redis;
using User.Api.Dto.Inspection;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class InspectionController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(InspectionController));
        private GdsfybjyWeiXinEntities _ctx;
        private static readonly string RedisInspectionKey = "GdsfybjyInspectionImage_";

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new GdsfybjyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取检查单列表
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="startDate"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetInspections")]
        public GetInspectionsResponse GetInspections(int cardId, string startDate)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCards.FirstOrDefault(x => x.CardId == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetInspectionsResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }

            var inpatientVisitId = "";
            var inpatientListRequest = new GetInPatientHisRequest();
            inpatientListRequest.CardNo = card.CardNo;

            //try
            //{
            //    var httpClient = InHttpClient.GetClient();
            //    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetInPatientHis", inpatientListRequest).Result;
            //    responseMsg.EnsureSuccessStatusCode();
            //    var inPatientListResponse = responseMsg.Content.ReadAsAsync<GetInPatientHisResponse>().Result;
            //    if (inPatientListResponse.ResultCode == "0")
            //    {
            //        var currentInpatient = inPatientListResponse.InPatientHisList
            //        .FirstOrDefault(x => x.IsInp == "1");
            //        if (currentInpatient != null)
            //        {
            //            inpatientVisitId = currentInpatient.VisitId;
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Logger.ErrorFormat("调用院内获取住院记录Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
            //}

            if (string.IsNullOrEmpty(inpatientVisitId))
            {
                var request = new GetExamInfoRequest();
                request.CardNo = card.CardNo;
                request.ItemType = "1";
                request.BeginDate = startDate.ToDateTimeOrDefault().ToString("yyyy-MM-dd");
                request.EndDate = startDate.ToDateTimeOrDefault().AddDays(15).ToString("yyyy-MM-dd");

                GetExamInfoResponse response;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetCheckReportInfo", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<GetExamInfoResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取检查单列表Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetInspectionsResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取检查单列表超时"
                    };
                }

                if (response.ResultCode != "0")
                {
                    return new GetInspectionsResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetInspectionsResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    IsInp = "0",
                    Inspections = response.ExamList.OrderBy(x => x.Status)
                        .ThenByDescending(x => x.ExamID)
                        .Select(x => new GetInspectionsResponse.Inspection
                        {
                            Id = x.ExamID,
                            Name = x.ExamName,
                            Date = x.ExamDate,
                            CardNo = x.CardNo,
                            PatientName = x.PatientName,
                            PatientSex = x.PatientSex,
                            Status = x.Status
                        }).ToList()
                };
            }
            else
            {
                var request = new InpGetExamInfoRequest();
                request.PatientId = card.CardNo;
                request.ItemType = "C";
                request.VisitId = inpatientVisitId;

                InpGetExamInfoResponse response;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("InPatientWs/InpGetExamInfo", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<InpGetExamInfoResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取住院化验单列表Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetInspectionsResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取化验单列表超时"
                    };
                }

                if (response.ResultCode != "0")
                {
                    return new GetInspectionsResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetInspectionsResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    IsInp = "1",
                    Inspections = response.ExamList.OrderBy(x => x.Status)
                        .ThenByDescending(x => x.ExamId)
                        .Select(x => new GetInspectionsResponse.Inspection
                        {
                            Id = x.ExamId,
                            Name = x.ExamName,
                            Date = x.ExamDate,
                            CardNo = x.CardNo,
                            PatientName = x.PatientName,
                            PatientSex = x.PatientSex,
                            Status = x.Status
                        }).ToList()
                };
            }
        }

        /// <summary>
        /// 获取检查单详情
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="appNo"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetInspectionImgUrls")]
        public GetInspectionImgUrlsResponse GetInspectionImgUrls(int cardId, string appNo)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCards.FirstOrDefault(x => x.CardId == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetInspectionImgUrlsResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }

            var inpatientVisitId = "";
            var inpatientListRequest = new GetInPatientHisRequest();
            inpatientListRequest.CardNo = card.CardNo;
           
            if (string.IsNullOrEmpty(inpatientVisitId))
            {
                var request = new GetCheckReportDetailRequest();
                request.CardNo = card.CardNo;
                request.ExamId = appNo;
                GetCheckReportDetailResponse response;
                Logger.ErrorFormat("调用院内获取检查单详情Api出错,信息：{0}，{1}", request.CardNo, request.ExamId);
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisSp/GetCheckReportDetail", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<GetCheckReportDetailResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取检查单详情Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetInspectionImgUrlsResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取检查详情超时"
                    };
                }

                if (response.ResultCode != "0")
                {
                    return new GetInspectionImgUrlsResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetInspectionImgUrlsResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    CheckItems = response.CheckItemList.Select(x => new GetInspectionImgUrlsResponse.CheckItem
                    {
                        ExamId = x.ExamId,
                        Prompt = x.Prompt,
                        Content = x.Content
                    }).ToList()
                };
            }
            else
            {
                var request = new InpGetExamDetailRequest();
                request.ExamId = appNo;
                request.ItemType = "D";

                InpGetExamDetailResponse response;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("InpatientWs/InpGetExamDetail", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<InpGetExamDetailResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内获取住院检查单详情Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetInspectionImgUrlsResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取检查单详情超时"
                    };
                }

                if (response.ResultCode != "0")
                {
                    return new GetInspectionImgUrlsResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetInspectionImgUrlsResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    CheckItems = response.ExamItemList.Select(x => new GetInspectionImgUrlsResponse.CheckItem
                    {

                        ExamId = x.ItemNo,
                        //ItemDate = x.ItemDate,
                        Prompt = x.ExamPrompt,
                        Content = x.ExamContent
                    }).ToList()
                };
            }
        }

        /// <summary>
        /// 获取化验单图片
        /// </summary>
        /// <param name="appNo"></param>
        /// <returns></returns>
        //[HttpGet]
        //[ActionName("GetInspectionImgUrls")]
        //public GetInspectionImgUrlsResponse GetInspectionImgUrls(string appNo)
        //{
        //    var request = new GetInspectionDetailRequest();
        //    request.AppNo = appNo;

        //    GetInspectionDetailResponse response;
        //    try
        //    {
        //        var httpClient = InHttpClient.GetClient();
        //        var responseMsg = httpClient.PostAsJsonAsync("LisWs/GetInspectionDetail", request).Result;
        //        responseMsg.EnsureSuccessStatusCode();
        //        response = responseMsg.Content.ReadAsAsync<GetInspectionDetailResponse>().Result;
        //    }
        //    catch (Exception ex)
        //    {
        //        Logger.ErrorFormat("调用院内获取化验单图片Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
        //        return new GetInspectionImgUrlsResponse
        //        {
        //            ResultCode = "1",
        //            ResultMsg = "获取化验单图片超时"
        //        };
        //    }

        //    if (response.ResultCode != "0")
        //    {
        //        return new GetInspectionImgUrlsResponse
        //        {
        //            ResultCode = "1",
        //            ResultMsg = response.ResultDesc
        //        };
        //    }

        //    var urls = new List<string>();
        //    using (var muxer = ConnectionMultiplexer
        //        .Connect(ConfigurationManager.AppSettings["Cache_Redis_Configuration"]))
        //    {
        //        var cache = muxer.GetDatabase();

        //        for (var i = 0; i < response.Images.Length; i++)
        //        {
        //            var image = response.Images[i];
        //            cache.StringSet(RedisInspectionKey + appNo + "_" + i, JsonConvert.SerializeObject(image),
        //                TimeSpan.FromMinutes(30));

        //            urls.Add(string.Format("{0}/api/Inspection/GetInspectionImg?appNo={1}&index={2}",
        //                ConfigurationManager.AppSettings["BaseAddress"],
        //                appNo,
        //                i));
        //        }
        //    }

        //    return new GetInspectionImgUrlsResponse
        //    {
        //        ResultCode = "0",
        //        ResultMsg = "",
        //        //ImgUrls = urls
        //    };
        //}

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="appNo"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        [ActionName("GetInspectionImg")]
        public HttpResponseMessage GetInspectionImg(string appNo, int index)
        {
            using (var muxer = ConnectionMultiplexer
                .Connect(ConfigurationManager.AppSettings["Cache_Redis_Configuration"]))
            {
                var cache = muxer.GetDatabase();

                var image = cache.StringGet(RedisInspectionKey + appNo + "_" + index);
                if (image.IsNullOrEmpty)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "未找到化验单图片");
                }

                var res = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(JsonConvert.DeserializeObject<byte[]>(image))
                };
                res.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
                return res;
            }
        }
    }
}
